<?php

namespace App\Http\Controllers;

use App\Http\Requests\RegisterAuthRequest;
use App\Models\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    protected $userModel;

    public function __construct()
    {
        $this->userModel = new User();
    }

    public function register(RegisterAuthRequest $request)
    {
        $user = new User();
        $user->name = $request->name;
        $user->password = bcrypt($request->password);
        $user->save();

        return $this->success($user);
    }

    public function login(Request $request)
    {

        $requestData = $this->validate($request, [
            'name' => 'required',
            'password' => 'required',
        ]);
//        ["name" => "admin", "password" => "123456"]
        if (!$token = auth('api')->attempt($requestData)) {
            return $this->fail();
        }
        return $this->respondWithToken($token);
    }

    public function respondWithToken($token)
    {
        return $this->success([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }

    public function user()
    {
        return $this->success(auth('api')->user());
    }

    public function logout()
    {
        auth('api')->logout();
        return $this->success();
    }

    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }
}
